import React, { Component } from 'react'
import { Form, Input, Button, Checkbox, message, notification, Modal } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import logo from './images/logo.png'
import memoryUtils from '../../utils/memoryUtils'
import storageUtils from '../../utils/storageUtils'
import { adduser, reqLogin } from '../../api'
import './index.less'
import { Redirect } from 'react-router-dom';
import Linkbutton from '../../components/link-button'
import Adduser from '../user/adduser';
const Item = Form.Item
export default class index extends Component {
	state = {
		visible:false
	}
	formRef = React.createRef();
	AdduserRef = React.createRef()
	onFinish = async (values) => {
		const result = await reqLogin(values.username, values.password)
		if (result.status === 0) {
			message.success('登录成功')
			memoryUtils.user = result.data
			storageUtils.saveUser(result.data)
			this.props.history.replace('/')
		} else {
			message.error('用户名或密码错误！')
		}
	};
	openNotification = () => {
  notification.open({
    message: '请联系管理员！',
    description:
      '管理员：admin，手机号：17816487882。',
  });
	};
	showAdduser = () => {
		this.setState({visible:true})
	}
	adduser = async () => {
		const user = await this.AdduserRef.current.validateFields()
		const { username, password, phone, email, role_id } = user

		const result = await adduser(username, password, phone, email, role_id )
		if (result.status === 0) {
			message.loading('注册成功，自动登录中...',0.5)
			const isLoad = await reqLogin(username, password)
			if (isLoad.status === 0) {
				message.success('登录成功')
			memoryUtils.user = isLoad.data
			storageUtils.saveUser(isLoad.data)
				this.props.history.replace('/')
  notification.open({
    message: '请联系管理员添加权限！',
    description:
      '管理员：admin，手机号：17816487882。',
  });
			} else {
				message.error('登录失败请稍后再试！')
			}
		} else {
			message.error(result.msg)
		}
	}
	render() {
		// 如果用户已经登陆, 自动跳转到admin
		if (memoryUtils.user && memoryUtils.user._id) {
			return <Redirect to='/' />
		}
		const {visible}=this.state
		return (
			<div className='login'>
				<header className='login-header'>
					<img src={logo} alt="logo" />
					<h1>React：后台管理系统</h1>
				</header>
				<section className='login-content'>
					<h2>用户登录</h2>
					<Form ref={this.formRef} name="normal_login" className="login-form"
						initialValues={{ remember: true }}
						onFinish={this.onFinish}>
						<Item name="username" rules={
							[
								{ required: true, message: '用户名必须填写！' },
								{ min: 4, max: 12, message: '请输入4-12位字符!' },
								// { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名必须是英文、数字或下划1111111111111111线组成!' },
								() => ({
									validator(_, value) {
										if (value === '') {
											return Promise.resolve('');
										}
										if (value.indexOf('习近平') === -1) {
											return Promise.resolve();
										}
										return Promise.reject('敏感词');
									},
								}),
							]
						}
						>
							<Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名" />
						</Item>
						<Item name="password" rules={[{ required: true, message: '请输入密码！' }]}>
							<Input prefix={<LockOutlined className="site-form-item-icon" />}
								type="password" placeholder="密码" />
						</Item>
						<Item>
							<Item name="remember" valuePropName="checked" noStyle>
								<Checkbox>记住我</Checkbox>
							</Item>
							<Linkbutton  onClick={this.openNotification} >忘记密码</Linkbutton>
						</Item>
						<Item>
							<Button type="primary" htmlType="submit" className="login-form-button" block>
								登录
                  </Button>没有账号？ <Linkbutton onClick={this.showAdduser}>点击注册!</Linkbutton>
						</Item>
					</Form>
				</section>
				<Modal visible={visible} onCancel={() => { this.setState({ visible: false }) }}
				onOk={this.adduser}>
					<Adduser AdduserRef={this.AdduserRef} roles={[]} Modaltitle={0}/>
				</Modal>
			</div>
		)
	}
}
